export type EnvironmentData = {
  temperature: number;
  humidity: number;
  pm25: number;
};

export class EnvService {
  private subscribers: Array<(data: EnvironmentData) => void> = [];
  private last: EnvironmentData = { temperature: 0, humidity: 0, pm25: 0 };

  subscribe(cb: (data: EnvironmentData) => void): () => void {
    this.subscribers.push(cb);
    cb(this.last);
    return () => {
      this.subscribers = this.subscribers.filter(fn => fn !== cb);
    };
  }

  update(data: EnvironmentData) {
    this.last = data;
    this.subscribers.forEach(fn => fn(data));
  }

  getLatest(): EnvironmentData {
    return this.last;
  }
}

export const envService = new EnvService();